package datastructure.book.tujiesuanfa.tree.bean;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * 序列化与反序列化二叉树
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        int cnt = 1;
        StringBuilder sb = new StringBuilder();
        while (!list.isEmpty()) {
            int tempCnt = 0;
            for (int i = 0; i < cnt; i++) {
                TreeNode node = list.removeFirst();
                if (node == null) {
                    sb.append("n").append("|");
                } else {
                    sb.append(node.val).append("|");
                    list.add(node.left);
                    list.add(node.right);
                    tempCnt+=2;
                }
            }
            cnt = tempCnt;
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        String[] split = data.split("\\|");
        TreeNode[] nodes = new TreeNode[split.length];
        for (int i = 0; i < split.length; i++) {
            if (!"n".equals(split[i])) {
                nodes[i] = new TreeNode(Integer.parseInt(split[i]));
            }
        }
        int cnt = 1;
        int index = 0;
        while (cnt > 0) {
            int tempCnt = 0;
            int nextSub = cnt;
            for (int i = 0; i < cnt; i++) {
                TreeNode node = nodes[index];
                if (node == null) {
                    nextSub-=1;
                } else {
                    node.left = nodes[index+nextSub];
                    node.right = nodes[index+nextSub+1];
                    tempCnt+=2;
                    nextSub+=1;
                }
                index++;
            }
            cnt = tempCnt;
        }
        return nodes[0];
    }

    public static void main(String[] args) {
        Codec codec = new Codec();
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3,node4,node5);
        TreeNode node1 = new TreeNode(1,node2,node3);
        String serialize = codec.serialize(node1);
        System.out.println(serialize);
        codec.deserialize(serialize);
    }
}
